<?php

namespace app\admin\controller;

use app\common\model\Type;
use houdunwang\arr\Arr;
use think\Controller;
use app\common\model\Category as CategoryModel;

/**
 *  Category
 *  分类控制器 admin.controller.Category
 * Class Login
 * @package app\admin\controller
 */
class Category extends Common
{
    protected $db;

    //模型初始化
    protected function _initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::_initialize();
        // TODO: Change the autogenerated stub   //TODO:自定义的初始化
        $this->db = new CategoryModel();
    }

    //分类首页
    public function lists()
    {
        $category = $this->db->lists();
//        p($category);die;

        $this->assign('category', $category);
        //加载模板
        return $this->fetch('lists');
    }

    //顶级分类添加
    public function addTop()
    {
        if (request()->isPost()) {
            $res = $this->db->addTop(input('post.'));
            if ($res['valid']) {
                //操作成功
                $this->success($res['msg'], 'lists');
                exit;
            } else {
                $this->error($res['msg']);
                exit;
            }
        }
        return $this->fetch('addTop');
    }

    //添加子级分类
    public function addSon()
    {
        $pid = input('param.pid');
        if (request()->isPost()) {
            $res = $this->db->addSon(input('post.'));
            if ($res['valid']) {
                //操作成功
                $this->success($res['msg'], 'lists');
                exit;
            } else {
                $this->error($res['msg']);
                exit;
            }
        } else {
            //1类型 获取数据表把该类型的tid带过去
            $typeList = (new Type())->lists();
            $this->assign('typeList', $typeList);
            //2通过隐藏域把pid父级id存入数据库
            $top = $this->db->find($pid);
            $this->assign('top', $top);

        }

        return $this->fetch('addSon');
    }

    //分类删除
    public function del()
    {

        $res = $this->db->del(input('param.cid'));
        if ($res['valid']) {
            //操作成功
            $this->success($res['msg'], 'admin/category/lists');
            exit;
        } else {
            $this->error($res['msg']);
            exit;
        }
    }
    //分类编辑
    public function edit()
    {
        //表单提交之后的操作
        if (request()->isPost()) {
            //p($_POST);die;
            //将post数据传入模型中操作
            $res = $this->db->edit(input('post.'));
            if ($res['valid']) {
                //执行成功
                $this->success($res['msg'], 'admin/category/lists');
                exit;
            } else {
                $this->error($res['msg']);
                exit;
            }
        }
        //变得提交之前的操作
        //接收tid
        $cid = input('param.cid');
        //获取旧数据
        $oldData = $this->db->find($cid);
//        p($oldData);die;
        $this->assign('oldData', $oldData);
        return $this->fetch('edit');
    }

}
